/*
 * Copyright (c) 2022-2023 cetcclout Co., Ltd All rights reserved.
 * Sensor Adapter is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.cetccloud.cimp.adapter.server.mqtt.subscribe;


import cn.hutool.json.JSONObject;
import com.cetccloud.cimp.adapter.protocol.StartOrStopServerService;
import com.cetccloud.cimp.adapter.server.mqtt.SystemContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.eclipse.paho.client.mqttv3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author
 * @Description TODO 订阅设备监控仪关系变更消息
 * @Date 2022/7/12 16:24
 */
@Component
@RequiredArgsConstructor
public class MqttServerStatusCallback implements MqttCallbackExtended {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${application.mqtt.shareGroup}")
    private String shareGroup;

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    @Autowired
    StartOrStopServerService startOrStopServerService;

    private static MqttAsyncClient mqttAsyncClient;
    public void setMqttAsyncClient(MqttAsyncClient mqttAsyncClient) {
        this.mqttAsyncClient = mqttAsyncClient;
    }

    /**
     * 建立订阅连接
     */
    @Override
    public void connectComplete(boolean reconnect, String serverURI) {
        logger.info("订阅服务的启动停止操作变更同步！！！");
        try {
            //订阅
            mqttAsyncClient.subscribe(shareGroup + SystemContext.MqTopic.SUB_START_OR_STOP_TOPIC, 2);
        } catch (MqttException e) {
            e.printStackTrace();
            logger.error("MqttException : {}", e.getMessage());
        }
    }

    /**
     * 连接中断
     */
    @Override
    public void connectionLost(Throwable cause) {
        // do nothing, just record, this cause has been processed by AutomaticReconnect option.
        logger.warn("connectionLost：{}", cause.toString());
    }

    /**
     * 接收订阅信息
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) {
        JSONObject jsonObject = null;
        try {
            jsonObject = OBJECT_MAPPER.readValue(message.getPayload(), JSONObject.class);
        } catch (IOException e) {
            logger.error("json error：{}", e.getMessage());
        }
        logger.info("收到的数据 : {}", jsonObject);
        //{msg=success, code=0, data={id=22, status=0}, success=true}
        if (jsonObject != null) {
            try {
                //处理数据
                startOrStopServerService.changeServerStatus(jsonObject);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("update data error: {}", e);
            }
        }
    }

    /**
     * 发送完成
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        logger.info("deliveryComplete---------{}" , token.isComplete());
    }

}
